<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1-拖拽</title>
    <style>
      #box {
        position: absolute;
        left: 0;
        top: 0;
        width: 100px;
        height: 100px;
        background: red;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      let box = document.querySelector("#box");
      let startMouse = {}; // 按下时，鼠标坐标
      let startOffset = {}; // 按下时，元素坐标
      // 鼠标移动的处理函数
      let move = (e) => {
        let nowMouse = {
          x: e.clientX,
          y: e.clientY,
        };
        let dis = {
          x: nowMouse.x - startMouse.x,
          y: nowMouse.y - startMouse.y,
        };
        let nowOffset = {
          x: dis.x + startOffset.x,
          y: dis.y + startOffset.y,
        };
        box.style.left = nowOffset.x + 'px';
        box.style.top = nowOffset.y + 'px';
      };
      box.addEventListener("mousedown", (e) => {
        startMouse = {
          x: e.clientX,
          y: e.clientY,
        };
        startOffset = {
          x: parseFloat(getComputedStyle(box)["left"]),
          y: parseFloat(getComputedStyle(box)["top"]),
        };
        document.addEventListener("mousemove", move);
        document.addEventListener(
          "mouseup",
          () => {
            document.removeEventListener("mousemove", move);
          },
          { once: true }
        );
      });
    </script>
  </body>
</html>
